package icu.xuyijie.springbootlearning2.chapter4.async;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 徐一杰
 * @date 2025/03/07 10:49
 * @description 线程池配置
 */
@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();

        // 修改线程池前缀名称
        threadPoolTaskExecutor.setThreadNamePrefix("徐一杰-");

        int availableProcessors = Runtime.getRuntime().availableProcessors();
        System.out.println("你的CPU线程数：" + availableProcessors);

        // 设置核心线程数量
        threadPoolTaskExecutor.setCorePoolSize(4);
        // 设置最大线程数量
        threadPoolTaskExecutor.setMaxPoolSize(8);
        // 设置等待队列的长度，只有在等待队列满的时候，才会开启新线程，否则一直使用核心线程
        threadPoolTaskExecutor.setQueueCapacity(4);
        // 配置拒绝策略，默认是 AbortPolicy，如果超出最大线程数，会直接拒绝执行该用户的请求并报错
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 设置程序结束时可以等待线程执行的最长时间
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        threadPoolTaskExecutor.setAwaitTerminationSeconds(1);

        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        threadPoolTaskScheduler.setPoolSize(4);

        threadPoolTaskScheduler.initialize();

        return threadPoolTaskScheduler;
    }

}
